import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {  message } from 'antd';
import moment from 'moment';
import { PrimaryGhostC, NoQueryC, DATA_ENTRY, AdvancedSearch, TableC, ContentPackage,TabC } from '../../../comps';
import myStyle from './index.less';
import { exportFile } from '../../../utils/commonFunc';
const FormItemLayout = {
  labelCol: {
    xs: { span: 4, offset: 0 },
    sm: { span: 8, offset: 0 },
    md: { span: 8, offset: 0 },
    lg: { span: 8, offset: 0 },
    xl: { span: 6, offset: 0 },
    xxl: { span: 5, offset: 0 },
  },
  wrapperCol: {
    xs: { span: 18, offset: 0 },
    sm: { span: 14, offset: 0 },
    md: { span: 14, offset: 0 },
    lg: { span: 14, offset: 0 },
    xl: { span: 17, offset: 0 },
    xxl: { span: 17, offset: 0 },
  },
};
@connect(({ SplitPipelineQueryM, userM: user, loading }) => ({
  SplitPipelineQueryM,
  user,
  loading,
}))
@Form.create()
export default class SplitPipelineQueryC extends PureComponent {
  state = {
    columnsReal: undefined,
    dataSourceReal: undefined, //真实交易流水
    columnsAdjust: undefined,
    dataSourceAdujst: undefined, //拆分交易流水
    currentPageReal: 1, //页码 真实
    numInPageReal: 20, //每页条数
    currentPageAdujst: 1, //页码 拆分
    numInPageAdjust: 20, //每页条数
    pageInfoReal: {}, //后端返回的页码信息 真实
    pageInfoAdjust: {}, //后端返回的页码信息 拆分
    searchObj: {}, //查询条件
    isReset: false, //是否点击重置
    isQuery: false, //是否点击了查询
    activeKey: '1', //tab默认显示真实交易
    rid: undefined, //真实交易id
  };
  componentDidMount() {}
  UNSAFE_componentWillReceiveProps(nextProps) {}

  //查询真实交易列表
  queryTableListReal = () => {
    const { searchObj, isReset, numInPageReal, currentPageReal } = this.state;
    if (isReset) {
      //判断是否点击了重置 点击页码不进行后台查询
      message.warning('您已重置查询字段，请设置条件后执行查询');
      return;
    }

    this.setState({
      columnsReal: undefined,
      dataSourceReal: undefined, //产品信息
      pageInfoReal: {},
    }); //查询之前清除数据
    const params = {
      listId: searchObj.listId,
      beginDate: searchObj.beginDate ? searchObj.beginDate.format('YYYY-MM-DD') : undefined,
      endDate: searchObj.endDate ? searchObj.endDate.format('YYYY-MM-DD') : undefined,
      currentPage: currentPageReal,
      numInPage: numInPageReal,
    };
    this.props.dispatch({
      type: 'SplitPipelineQueryM/queryTableListReal',
      payload: {
        ...params,
      },
      callback: (type, data) => {
        if (type == 'success') {
          data.dataSource.map((item, key) => {
            item.key = key;
          });
          this.setState({
            columnsReal: data.columns ? [...data.columns] : [],
            dataSourceReal: data.dataSource ? [...data.dataSource] : [],
            pageInfoReal: data.pageInfo || {},
          });
        } else {
          this.setState({
            columnsReal: [],
            dataSourceReal: [],
            pageInfoReal: {},
          });
        }
      },
    });
  };
  //查询拆分交易列表
  queryTableListAdjust = () => {
    const { searchObj, isReset, numInPageAdjust, currentPageAdujst, rid } = this.state;
    if (isReset) {
      //判断是否点击了重置 点击页码不进行后台查询
      message.warning('您已重置查询字段，请设置条件后执行查询');
      return;
    }

    this.setState({
      columnsAdjust: undefined,
      dataSourceAdujst: undefined,
      pageInfoAdjust: {},
    }); //查询之前清除数据
    const params = {
      listId: searchObj.listId,
      beginDate: searchObj.beginDate ? searchObj.beginDate.format('YYYY-MM-DD') : undefined,
      endDate: searchObj.endDate ? searchObj.endDate.format('YYYY-MM-DD') : undefined,
      currentPage: currentPageAdujst,
      numInPage: numInPageAdjust,
    };
    if (rid) params.rid = rid;

    this.props.dispatch({
      type: 'SplitPipelineQueryM/queryTableListAdjust',
      payload: {
        ...params,
      },
      callback: (type, data) => {
        if (type == 'success') {
          data.dataSource.map((item, key) => {
            item.key = key;
          });
          this.setState({
            columnsAdjust: data.columns ? [...data.columns] : [],
            dataSourceAdujst: data.dataSource ? [...data.dataSource] : [],
            pageInfoAdjust: data.pageInfo || {},
          });
        } else {
          this.setState({
            columnsAdjust: [],
            dataSourceAdujst: [],
            pageInfoAdjust: {},
          });
        }
      },
    });
  };

  //表格页码排序改变调用
  handleTableChangeReal = (pagination, filter, sorter) => {
    const { current, pageSize } = pagination;
    this.setState(
      {
        currentPageReal: current,
        numInPageReal: pageSize,
      },
      () => {
        this.queryTableListReal();
      },
    );
  };
  //表格页码排序改变调用
  handleTableChangeAdjust = (pagination, filter, sorter) => {
    const { current, pageSize } = pagination;
    this.setState(
      {
        currentPageAdujst: current,
        numInPageAdjust: pageSize,
      },
      () => {
        this.queryTableListAdjust();
      },
    );
  };
  exportFileFun = (url, params) => {
    this.advancedSearch.props.form.validateFields((error, values) => {
      if (error) {
        message.warning('请完善查询条件!');
        return;
      } else {
        //当重置情况下,需要提示重新查询
        if (this.state.isReset) {
          message.warning('条件已重置!请重新查询后再进行导出!');
          return;
        }
        exportFile(url, params); //导出表格
      }
    });
  };
  //拆分
  download = () => {
    const { searchObj, numInPageAdjust, currentPageAdujst, rid } = this.state;
    const params = {
      listId: searchObj.listId,
      beginDate: searchObj.beginDate ? searchObj.beginDate.format('YYYY-MM-DD') : undefined,
      endDate: searchObj.endDate ? searchObj.endDate.format('YYYY-MM-DD') : undefined,
    };
    if (rid) params.rid = rid;
    this.exportFileFun('api/v1/assetSplit/exportAssetSplit/exportSplitTradeListByDate', params);
  };
  //表格列表 拆分交易
  initTableAdjust = () => {
    const { searchObj, rid, currentPageAdujst, numInPageAdjust, columnsAdjust, dataSourceAdujst, pageInfoAdjust } = this.state;
    columnsAdjust &&
      columnsAdjust.map((item) => {
        item.width=110;
        if (item.key == 'tradeAmount' || item.key == 'tradePrice') {
          item.type = 'money';
          if (item.key == 'tradePrice') {
            item.toFixed = 4;
          }
        }
        if (item.key == 'buyRate') {
          item.type = 'rate';
          if (item.key == 'buyRate') item.toFixed = 4;
        }
        if (item.key == 'tradeNum') {
          item.type = 'number';
        }
        if(item.key=='secuName' ||item.key=='productName'){
          item.width=180;
          item.ellipsis=true;
        }
      });

    return (
      <div>
        <div className={myStyle.topDiv}>
          <div className='top_title'>
            {!rid
              ? `${searchObj.beginDate ? searchObj.beginDate.format('YYYY-MM-DD') : moment().format('YYYY-MM-DD')}~${
                  searchObj.endDate ? searchObj.endDate.format('YYYY-MM-DD') : moment().format('YYYY-MM-DD')
                }区间内的所有拆分交易流水`
              : `${searchObj.beginDate ? searchObj.beginDate.format('YYYY-MM-DD') : moment().format('YYYY-MM-DD')}~${
                  searchObj.endDate ? searchObj.endDate.format('YYYY-MM-DD') : moment().format('YYYY-MM-DD')
                }区间内单笔交易的拆分交易流水`}
          </div>
          <PrimaryGhostC title='导出' onClick={this.download} />
        </div>
        <TableC
          columns={columnsAdjust}
          dataSource={dataSourceAdujst}
          onChange={this.handleTableChangeAdjust}
          selfScrollY={true}
          current={currentPageAdujst}
          total={pageInfoAdjust.total || 0}
          pageSize={numInPageAdjust}
          rowKey='id'
        />
      </div>
    );
  };
  //真实交易 导出
  exportFile = () => {
    const { searchObj, numInPageAdjust, currentPageAdujst, rid } = this.state;
    const params = {
      listId: searchObj.listId,
      beginDate: searchObj.beginDate ? searchObj.beginDate.format('YYYY-MM-DD') : undefined,
      endDate: searchObj.endDate ? searchObj.endDate.format('YYYY-MM-DD') : undefined,
    };
    this.exportFileFun('api/v1/assetSplitRealTradeFlow/exportTradeListByDate', params);
  };
  //表格列表 真实交易
  initTableReal = () => {
    const { currentPageReal, numInPageReal, columnsReal, dataSourceReal, pageInfoReal } = this.state;
    if (columnsReal && columnsReal.length && columnsReal[columnsReal.length - 1].key != 'operate') {
      columnsReal.push({
        key: 'operate',
        type: 'operate',
        title: '操作',
        fixed: 'right',
        width: 100,
        operates: [
          {
            title: '查看拆分',
            onClick: (record, index) => {
              this.setState(
                {
                  activeKey: '2',
                  rid: record.id,
                },
                () => {
                  this.queryTableListAdjust();
                },
              );
            },
          },
        ],
      });
    }
    columnsReal &&
      columnsReal.map((item) => {
        item.width=110;
        if (item.key == 'tradeAmount' || item.key == 'tradePrice') {
          item.type = 'money';
          if (item.key == 'tradePrice') {
            item.toFixed = 4;
          }
        }
        if (item.key == 'buyRate') {
          item.type = 'rate';
          if (item.key == 'buyRate') item.toFixed = 4;
        }
        if (item.key == 'tradeTotalNum') {
          item.type = 'number';
        }
        if(item.key=='secuName'){
          item.width=180;
          item.ellipsis=true;
        }
      });

    return (
      <div>
        <div style={{ textAlign: 'right', marginBottom: '10px' }}>
          <PrimaryGhostC title='导出' onClick={this.exportFile} />
        </div>
        <TableC
          columns={columnsReal}
          dataSource={dataSourceReal}
          onChange={this.handleTableChangeReal}
          current={currentPageReal}
          total={pageInfoReal.total || 0}
          selfScrollY={true}
          pageSize={numInPageReal}
          rowKey='id'
        />
      </div>
    );
  };

  //TAb页切换发生事件
  tabsonClick = (key) => {
    this.setState({
      activeKey: key,
    });
  };
  render() {
    const { isQuery, activeKey } = this.state;
    const searchProps = {
      dataSource: [
        {
          dataIndex: ['beginDate', 'endDate'],
          title: '时间区间',
          type: DATA_ENTRY.RANGEDATE,
          initialValue: [moment(), moment()],
          onRef: (ref) => {
            this.setState({ RangeDateC: ref });
          },
          formItemLayout: FormItemLayout,
        },
        {
          dataIndex: 'listId',
          title: '系列产品',
          type: DATA_ENTRY.SERIESPRODUCTS,
          rules: [{ required: true, message: '请选择系列产品!' }],
          allowClear: false,
          onRef: (ref) => (this.series = ref),
        },
      ],
      onQuery: (e) => {
        this.advancedSearch.props.form.validateFields((err, fieldsValue) => {
          if (!err) {
            this.setState(
              {
                searchObj: e,
                currentPageReal: 1,
                currentPageAdujst: 1,
                isReset: false,
                isQuery: true,
                rid: undefined, //点击查询重置真实交易id
              },
              () => {
                this.queryTableListAdjust(); //点击查询按钮
                this.queryTableListReal(); //点击查询按钮
              },
            );
          }
        });
      },
      onClear: () => {
        //点击重置按钮
        this.setState({
          searchObj: {},
          isReset: true,
          selectProductList: [],
        });
      },
      onRef: (ref) => {
        this.advancedSearch = ref;
      },
    };

    return (
      <ContentPackage
        title='拆分流水查询'
        contentHtml={
          <div className={myStyle.splitPipelineQuery}>
            <div className={'cardBody'}>
              <AdvancedSearch {...searchProps} />
            </div>
            <TabC
              tabSource={[
                { title: '真实交易流水', key: '1', content: isQuery ?  this.initTableReal() : <NoQueryC /> },
                { title: '拆分交易流水', key: '2', content: isQuery ? this.initTableAdjust() : <NoQueryC /> },
              ]}
              activeKey={activeKey}
              onChange={this.tabsonClick}
              />
          </div>
        }
      />
    );
  }
}
